package com.cyj.user.controller;

import com.cyj.user.entity.User;
import com.cyj.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @GetMapping("/")
    public String showLoginForm(Model model, @RequestParam(required = false) String redirectUrl) {
        model.addAttribute("redirectUrl", redirectUrl);

        return "/login";
    }
    @PostMapping("/login")
    public String login(String username, String password, Model model, HttpSession session) {
        User user = userService.selectUserByUsernameAndPassword(username, password);
        if (user!= null) {
            session.setAttribute("loggedInUser", user);
            return "redirect:/users/list";
        } else {
            model.addAttribute("error", "Invalid username or password");
            return "/login";
        }
    }

}